#! /usr/bin/env python
# -*- coding: utf-8 -*-

"""
Расчет грида плотности распределения точек
"""

import sys
from optparse import OptionParser
from plane import Plane
from grid_plane import PlaneGrid

def line_parse(line):
    line = line.expandtabs(1)
    line = [x for x in line.split(' ') if x != '' ]    
    DIP, DIR = 0, 0    
    
    try:
        DIR, DIP = int(line.pop(0)), int(line.pop(0))
    except:
        #sys.stdout.write('WARNING! Cannot parse string: %s\n' % line)
        return None   
    line = Plane(DIR, DIP)
    return line

# Parsing of an options
optparser= OptionParser()
optparser.add_option('-n', '--cell size', dest='gsize',
                     help='size of a net cell',
                     default=5)

options, args = optparser.parse_args(sys.argv[1:])

lines = sys.stdin.read().split('\n')

# parsing of the data
data=[]
for line in lines:
    val = line_parse(line)
    if val != None: data.append(val)  

   

# finding the dinsity grid
grid = PlaneGrid((int(options.gsize), int(options.gsize)))

mval = 0
for ddir in range(0, 360, int(options.gsize)):
    for ddip in range(0, 89, int(options.gsize)):
        cell_plane = Plane(ddir, ddip)
        for plane_ in data:            
            # angle between normal of two planes
            angle = cell_plane.return_angle_between(plane_)
            if angle < int(options.gsize):                
                grid.add(plane=cell_plane, val=2)
                mval = max(grid.get(plane=cell_plane),mval)                
            elif angle < 2*int(options.gsize):                
                grid.add(plane=cell_plane, val=1)
                mval = max(grid.get(plane=cell_plane),mval)
            elif angle < 3*int(options.gsize):                
                grid.add(plane=cell_plane, val=0.5)
                mval = max(grid.get(plane=cell_plane),mval)
ddir = 0
ddip = 90
cell_plane=Plane(0,90)
g90=0
for plane_ in data:     
# angle between normal of two planes
    angle = cell_plane.return_angle_between(plane_)
    if angle < int(options.gsize):                
        g90+=2
        mval = max(g90,mval)                
    elif angle < 2*int(options.gsize):                
        g90+=1
        mval = max(g90,mval)
    elif angle < 3*int(options.gsize):                
        g90+=0.5
        mval = max(g90,mval)

                
mval = mval*1.0
sys.stdout.write('%2.2f\n' % (int(options.gsize)))
for ddir in range(0, 360, int(options.gsize)):
    for ddip in range(0, 90, int(options.gsize)):
        a = Plane(ddir,ddip)
        sys.stdout.write('%d\t%d\t%0.2f\n' % (a.dir, a.dip, grid.get(plane=a)/mval))
for ddir in range(0, 360, int(options.gsize)):
    a = Plane(ddir, 90)
    sys.stdout.write('%d\t%d\t%0.2f\n' % (a.dir, 90, g90/mval))
